package com.byit.ueditor.upload;

import com.byit.ueditor.PathFormat;
import com.byit.ueditor.define.AppInfo;
import com.byit.ueditor.define.BaseState;
import com.byit.ueditor.define.FileType;
import com.byit.ueditor.define.State;
import com.byit.utils.SpringUtil;
import io.minio.MinioClient;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.util.Map;


/**
 * MinIo上传涂鸦图片
 */
public final class MinioBase64Uploader {

	private static Logger log = LoggerFactory.getLogger(MinioBase64Uploader.class);

	public static State save(String content, Map<String, Object> conf) {
		
		byte[] data = decode(content);

		long maxSize = ((Long) conf.get("maxSize")).longValue();

		if (!validSize(data, maxSize)) {
			return new BaseState(false, AppInfo.MAX_SIZE);
		}

		String suffix = FileType.getSuffix("JPG");

		String savePath = PathFormat.parse((String) conf.get("savePath"),
				(String) conf.get("filename"));
		
		savePath = savePath + suffix;
		String physicalPath = (String) conf.get("rootPath") + savePath;



        // 获取Minio实例
        MinioClient minioClient = SpringUtil.getBean(MinioClient.class);

        String format = "/tuya/{yyyy}{mm}{dd}/{time}{rand:6}";
        String objectName = PathFormat.parse(format) + suffix;



        String bucketName = "ueditor";

        try {
            ByteArrayInputStream fileStream = new ByteArrayInputStream(data);
            minioClient.putObject(bucketName, objectName, fileStream, "application/x-jpg");



            State storageState = new BaseState(true);
            storageState.putInfo( "size", maxSize );
            storageState.putInfo("url", bucketName + objectName );
            storageState.putInfo("type", suffix);
            storageState.putInfo("original", "");

            return storageState;
        } catch (Exception e) {
            log.error("", e);
            return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
        }

	}

	private static byte[] decode(String content) {
		return Base64.decodeBase64(content);
	}

	private static boolean validSize(byte[] data, long length) {
		return data.length <= length;
	}
	
}